#include "AmbientLight.h"
#include "ILogger.h"


AmbientLight::AmbientLight(IArduino& arduino, MessageRouter& router, const String& name, ILogger& logger, const String& buttonName,
	const String& lightCircuit,	const String& montionTrigger, long lightDelay): 
SimpleLight(arduino, router, name, logger, buttonName, lightCircuit), montionTrigger_(allocateString(montionTrigger)),
state_(READY), lightDelay_(lightDelay), lastMontion_(0){
}
AmbientLight::~AmbientLight(){
	free(static_cast<void*>(montionTrigger_));
}
void AmbientLight::tick(long milliseconds) {
	if(circuitState_ && ((milliseconds - lastMontion_) > lightDelay_)){
		logger_.log("bubiczka");
		logger_.log(String("milliseconds: ") + milliseconds);
		logger_.log(String("lastMontion_: ") + lastMontion_);
		logger_.log(String("lightDelay_: ") + lightDelay_);
		circuitState_ = false;
		publishCircuitState();
	}
}
bool AmbientLight::onItem(const String& name, const String& value){
	switch(state_){
			  case READY:
				  if(name == F("event") && value == F("button")){
					  state_ = BUTTON_EVENT;
					  return true;
				  }
				  if(name == F("event") && value == F("montion")){
					  state_ = MONTION_EVENT;
					  return true;
				  }
				  break;
			  case BUTTON_EVENT:
				  if(name == F("id") && value == buttonName_){
					  return true;
				  }
				  if(name == F("state") && value == F("on")){
					  circuitState_ = !circuitState_;
					  lastMontion_ = arduino_.milliseconds();
					  publishCircuitState();
					  state_ = READY;
					  return false;
				  }
				  break;
			  case MONTION_EVENT:
				  if(name == F("id") && value == montionTrigger_){
					  lastMontion_ = arduino_.milliseconds();
					  circuitState_ = true;
					  publishCircuitState();
					  state_ = READY;
					  return false;
				  }
				  break;
	}
	state_ = READY;
	return false;
}
